#include "formkeyboard.h"
#include "ui_formkeyboard.h"

#include <QDebug>
#include <QTime>
#include <QCoreApplication>
#include <QEventLoop>

void FormKeyBoard::delay_ms(unsigned int ms)
{
    QTime endTime = QTime::currentTime().addMSecs(ms);
    while (QTime::currentTime() < endTime) {
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
    }
}

FormKeyBoard::FormKeyBoard(QWidget *parent, QLineEdit* input) :
    QWidget(parent),
    ui(new Ui::FormKeyBoard)
{
    if (key_board_info.opened) {
        this->deleteLater();
        return;
    }

    ui->setupUi(this);
    key_board_info.capa = 0;
    key_board_info.mode = 0;
    key_board_info.opened = 1;
    inputObj = input;  // QPointer 自动管理

    // 初始化按钮数组
    btn_obj[0] = ui->pushButton_2;
    btn_obj[1] = ui->pushButton_3;
    btn_obj[2] = ui->pushButton_4;
    btn_obj[3] = ui->pushButton_5;
    btn_obj[4] = ui->pushButton_6;
    btn_obj[5] = ui->pushButton_7;
    btn_obj[6] = ui->pushButton_8;
    btn_obj[7] = ui->pushButton_9;
    btn_obj[8] = ui->pushButton_10;
    btn_obj[9] = ui->pushButton_11;
    btn_obj[10] = ui->pushButton_12;
    btn_obj[11] = ui->pushButton_13;
    btn_obj[12] = ui->pushButton_14;
    btn_obj[13] = ui->pushButton_15;
    btn_obj[14] = ui->pushButton_16;
    btn_obj[15] = ui->pushButton_17;
    btn_obj[16] = ui->pushButton_18;
    btn_obj[17] = ui->pushButton_19;
    btn_obj[18] = ui->pushButton_20;
    btn_obj[19] = ui->pushButton_21;
    btn_obj[20] = ui->pushButton_22;
    btn_obj[21] = ui->pushButton_23;
    btn_obj[22] = ui->pushButton_24;
    btn_obj[23] = ui->pushButton_25;
    btn_obj[24] = ui->pushButton_26;
    btn_obj[25] = ui->pushButton_27;
    btn_obj[26] = ui->pushButton_28;
    btn_obj[27] = ui->pushButton_29;
    btn_obj[28] = ui->pushButton;  // Del 键

    for (int i = 0; i < 29; ++i) {
        connect(btn_obj[i], &QPushButton::clicked, this, [=]() {
            btn_keyBoard_clicked(static_cast<uint8_t>(i));
        });
    }

    keyBoard_mode(0);

    if (inputObj) {
        ui->lineEdit->setText(inputObj->text());
    }

    this->move((parent->width() - this->width()) / 2, parent->height() - this->height());
    this->show();
}

FormKeyBoard::~FormKeyBoard()
{
    delete ui;
}

int FormKeyBoard::isOpend()
{
    return key_board_info.opened;
}

void FormKeyBoard::Close()
{
    key_board_info.opened = 0;
    this->deleteLater();
}

void FormKeyBoard::setInputLineEdit(QLineEdit *obj)
{
    inputObj = obj;
    if (inputObj) {
        ui->lineEdit->setText(inputObj->text());
    }
    this->show();
}

// 👇 核心修复：全部使用 QString
void FormKeyBoard::btn_keyBoard_clicked(uint8_t index)
{
    if (!inputObj) {
        qDebug() << "Input object is null!";
        return;
    }

    QPushButton* btn = qobject_cast<QPushButton*>(sender());
    if (!btn) return;

    QString btnText = btn->text();

    // 功能键处理
    if (btnText == "Caps") {
        key_board_info.capa = !key_board_info.capa;
        btn->setText("CAPS");
        keyBoard_mode(1);
        return;
    } else if (btnText == "CAPS") {
        key_board_info.capa = !key_board_info.capa;
        btn->setText("Caps");
        keyBoard_mode(0);
        return;
    } else if (btnText == "?123") {
        keyBoard_mode(2);
        return;
    } else if (btnText == "Back") {
        key_board_info.capa = 0;
        keyBoard_mode(0);
        return;
    } else if (btnText == "More") {
        if (key_board_info.mode == 2) {
            keyBoard_mode(3);
        } else if (key_board_info.mode == 3) {
            keyBoard_mode(2);
        }
        return;
    } else if (btn == ui->pushButton) { // Del 键
        QString current = inputObj->text();
        if (!current.isEmpty()) {
            current.chop(1); // 安全删除最后一个字符
            inputObj->setText(current);
            ui->lineEdit->setText(current);
        }

        // 按键高亮
        btn_obj[index]->setStyleSheet("QPushButton{"
                                      "border: 0px;"
                                      "border-radius:2px;"
                                      "color:rgb(255, 255, 255);"
                                      "background-color: rgb(239, 41, 41);}");
        delay_ms(150);
        btn_obj[index]->setStyleSheet("QPushButton{"
                                      "border: 0px;"
                                      "border-radius:2px;"
                                      "color:rgb(255, 255, 255);"
                                      "background-color: rgb(255, 255, 255);}");
        return;
    }

    // 普通字符输入
    QString ch = btnText;

    // 如果是字母且未大写锁定，则转小写（注意：原逻辑有误，这里修正）
    if (key_board_info.mode == 0 || key_board_info.mode == 1) {
        if (!key_board_info.capa && ch.size() == 1 && ch[0].isLetter()) {
            ch = ch.toLower();
        }
    }

    // 追加字符
    QString newText = inputObj->text() + ch;
    inputObj->setText(newText);
    ui->lineEdit->setText(newText); // 同步内部显示

    // 按键高亮
    btn_obj[index]->setStyleSheet("QPushButton{"
                                  "border: 0px;"
                                  "border-radius:2px;"
                                  "color:rgb(255, 255, 255);"
                                  "background-color: rgb(0, 153, 255);}");
    delay_ms(150);
    btn_obj[index]->setStyleSheet("QPushButton{"
                                  "border: 0px;"
                                  "border-radius:2px;"
                                  "color:rgb(0, 0, 0);"
                                  "background-color: rgb(255, 255, 255);}");
}

// 键盘布局数据（注意：第3行 "&&" 应为 "&"，否则显示两个 &）
const char *keyBoardCh[4][30] = {
    {"q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","Caps","z","x","c","v","b","n","m","?123","Del"},
    {"Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","CAPS","Z","X","C","V","B","N","M","?123","Del"},
    {"1","2","3","4","5","6","7","8","9","0",",",";",".",":","?","[","]","<",">","More","+","-","*","/","=","_"," ","Back","Del"},
    {"!","@","#","$","%","^","&","*","(",")","~","`","{","}","|","","","","","More","","","","","","","","Back","Del"}, // 修正 "&&" -> "&"
};

void FormKeyBoard::keyBoard_mode(int mode)
{
    for (int i = 0; i < 28; ++i) {
        btn_obj[i]->setText(QString::fromUtf8(keyBoardCh[mode][i]));
    }
    key_board_info.mode = mode;
}

// Del 键槽（实际由 btn_keyBoard_clicked 处理，可留空）
void FormKeyBoard::on_pushButton_clicked()
{
    // 无需实现，已由 btn_keyBoard_clicked(index=28) 处理
}

// 关闭键盘
void FormKeyBoard::on_pushButton_30_clicked()
{
    key_board_info.opened = 0;
    this->deleteLater();
    emit formkeyboard_close_signal();
}
